package ro.sobis.repetor;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class EncryptDecrypt {
    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public EncryptDecrypt() throws Exception {
        myEncryptionKey = "Used4LogonUsed4LogonUsed";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public byte[] encrypt(String unencryptedString) throws InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
    	byte[] encryptedText=null;
        
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            encryptedText = cipher.doFinal(plainText);
           
       
        return encryptedText;
    }


    public String decrypt(byte[] encryptedString) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        String decryptedText=null;
       
            cipher.init(Cipher.DECRYPT_MODE, key);
            
            byte[] plainText = cipher.doFinal(encryptedString);
            decryptedText= new String(plainText);
       
        return decryptedText;
    }

}
